/**
 *
 */
package com.googlecode.bip.entity;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * @author Claude
 *
 */
public class EntityHelper
{
    private EntityHelper()
    {
        //All static
    }

    /**
     * Create normalized Timestamp from initialized Calendar
     * @param calendar initialized Calendar
     * @return normalized Timestamp
     */
    public static Timestamp getNormalizedTimestamp(
            final Calendar calendar
            )
    {
        calendar.set( Calendar.MILLISECOND, 0 );   // ignore milliseconds
        calendar.set( Calendar.SECOND, 0 );        // ignore seconds
        calendar.set( Calendar.MINUTE, 0 );        // ignore minutes
        calendar.set( Calendar.HOUR, 0 );          // ignore hours
        calendar.set( Calendar.AM_PM, 0 );         // ignore AM/PM (1 value per day)

        Timestamp nts = new Timestamp( calendar.getTimeInMillis() );

        return nts;
    }

    /**
     * TODO
     * @param date (could be null)
     * @param userTimeZone (used to initialized date from server date + user timezone)
     * @return normalized Timestamp
     */
    public static Timestamp getNormalizedTimestamp(
            final Date      date,
            final TimeZone  userTimeZone
            )
    {
        Calendar c = new GregorianCalendar();

        if( date != null ) {
            c.setTime( date );
            }
        // else use current date/time
        // TODO: warning this is server date/time (not user !!!)
        // should be user date/time TODO use userTimeZone

        return getNormalizedTimestamp( c );
    }

    /**
     *
     * @param date a valid Date/Timestamp that must be normalized
     * @return normalized Timestamp
     */
    public static Timestamp getNormalizedTimestamp(
            final Date date
            )
    {
        Calendar c = new GregorianCalendar();

        if( date == null ) {
            throw new NullPointerException( "date is null" );
            }

        c.setTime( date );

        return getNormalizedTimestamp( c );
    }

    /**
     * Check is giving String contain only alpha numerics characters,
     * no white spaces
     * @param str
     * @return
     */
    public static boolean isValidAlphanumericNoWhiteSpaces( final String str )
    {
        final int l = str.length();

        for(int i = 0; i<l; i++ ) {
            if( !Character.isLetterOrDigit( str.charAt( i ) ) ) {
                return false;
            }
        }

        return true;
    }

}
